
package com.yytek.tcp.impl;

import com.yytek.common.core.domain.R;
import com.yytek.common.core.domain.AttributeInfo;
import com.yytek.common.core.domain.Device;
import com.yytek.common.web.domain.ThingModelMessage;
import com.yytek.gw.service.DriverCustomService;
import com.yytek.gw.service.DriverMsgCommonService;
import com.yytek.tcp.netty.ModbusTcp.NettyModBusTcpServer;
import com.yytek.tcp.netty.tcp.NettyTcpServer;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 驱动实现
 */
@Slf4j
@Service
public class DriverCustomServiceImpl implements DriverCustomService {

    @Value("${driver.port}")
    private Integer driverPort;

    @Resource
    private NettyTcpServer nettyTcpServer;
    @Resource
    private NettyModBusTcpServer nettyModBusTcpServer;
    @Resource
    private DriverMsgCommonService driverMsgCommonService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public void initial() {
        threadPoolExecutor.execute(() -> {
            log.info("Virtual Listening Driver Starting(TCP::{}) incoming data listener", driverPort);
            //nettyTcpServer.start(driverPort);
            nettyModBusTcpServer.start(driverPort);
        });
    }

    @Override
    public R read(Map<String, AttributeInfo> driverInfo, Map<String, AttributeInfo> dataInfo, Device device) throws Exception {
        // 因为 Listening Virtual 的数据来源是被动接收的，所以无需实现该 Read 方法
        // 接收数据处理函数在
        // - com.dc3.driver.service.netty.tcp.NettyTcpServerHandler.channelRead
        // - com.dc3.driver.service.netty.udp.NettyUdpServerHandler.channelRead0
        return R.ok();
    }

    @Override
    public R  write(Map<String, AttributeInfo> driverInfo, Map<String, AttributeInfo> dataInfo, Device device) throws Exception {
        String deviceId = device.getIotId();
        // TODO 获取设备的Channel，并向下发送数据
        Channel channel = NettyTcpServer.biDirectionHashMap.getByKey(deviceId);
        if (null != channel) {
            //编码后的数据
            Object sendMsg = driverMsgCommonService.anaylisToMsg(deviceId, (ThingModelMessage) dataInfo.get("data").getValue());
            //下发data中的数据
            channel.writeAndFlush(sendMsg);
        }
        return R.ok();
    }


}
